export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
	}),
	mutations: {
		// 商品加入购物车
		joinCartFun(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.commit('my_cart/saveStorage')
		},
		saveStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateGoodsState(state, goods) {
			const result = state.cart.find(x => x.goods_id === goods.goods_id)
			if (result) {
				result.goods_state = goods.goods_state
				this.commit('my_cart/saveStorage')
			}
		},
		updateGoodsCount(state, goods) {
			const result = state.cart.find(x => x.goods_id === goods.goods_id)
			if (result) {
				result.goods_count = goods.goods_count
				this.commit('my_cart/saveStorage')
			}
		},
		removeGoodsItem(state, goods_id) {
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateAllcheckState(state,newState){
			state.cart.forEach(item=>item.goods_state = newState)
			this.commit('my_cart/saveStorage')
		}
	},
	getters: {
		total(state) {
			return state.cart.reduce((sum, item) => sum + item.goods_count, 0)
		},
		checkedEvery(state) {
			return state.cart.filter(item => item.goods_state).reduce((total,item)=>total += item.goods_count,0)
		},
		checkedPriceCount(state){
			return state.cart.filter(item=>item.goods_state).reduce((sum,item)=>sum += item.goods_count*item.goods_price,0).toFixed(2)
		}
	}
}